const fs = require("fs");
const PATH = require("path");
const path = require("path");
const { exec } = require("child_process");

function isDir(fileDir) {
  return new Promise((resolve, reject) => {
    fs.stat(fileDir, function (err, stats) {
      if (stats.isDirectory()) resolve(true);
      resolve(false);
    });
  });
}

async function createCmd(path) {
  let readDir = fs.readdirSync(path);
  for (const folder of readDir) {
    const fileDir = PATH.join(path, folder);
    const isFolder = await isDir(fileDir);
    if (!isFolder) continue;

    let tsFiles = fs.readdirSync(fileDir);
    tsFiles = tsFiles.filter((i) => i.length < 4).sort((a, b) => a - b);

    const concatFilePath = PATH.join(dirPath, folder);

    let cmdStr = `ffmpeg -y -i "concat:${tsFiles.join("|")}" -c copy ${concatFilePath}.mp4`;
    // console.log("TT > cmdStr", cmdStr);
    exec(cmdStr, { cwd: fileDir }, (error, stdout, stderr) => {
      if (error) {
        console.error(error);
        return;
      }
      // _deleteDir(fileDir)
      // console.log('TT > stdout', stdout)
    });
  }
}

const dirPath = "D:/2RJ/1/";
createCmd(dirPath);


/**
 * @caption 删除本地文件夹/文件
 * @param {String} directoryPath 例： d://x/x/x.json 或者 d://x/x/x
 * *@param {Function} callback 例：回调
 */
function _deleteDir(directoryPath, callback) {
  const fs = require("fs").promises;
  async function rmdirAsync(directoryPath) {
    try {
      let stat = await fs.stat(directoryPath);
      if (stat.isFile()) {
        await fs.unlink(directoryPath);
      } else {
        let dirs = await fs.readdir(directoryPath);
        // 递归删除文件夹内容(文件/文件夹)
        dirs = dirs.map((dir) => rmdirAsync(path.join(directoryPath, dir)));
        await Promise.all(dirs);
        await fs.rmdir(directoryPath);
      }
    } catch (e) {
       
      console.error(e);
    }
  }
  require("fs").existsSync(directoryPath) &&
    rmdirAsync(directoryPath).then(() => {
      // 确保文件/文件夹均已删除 => 回调
      callback && callback();
    });
}
